import Vue from 'vue';

const ToptipConstructor = Vue.extend(require('./toptip.vue'));

const instance = new ToptipConstructor({
    el: document.createElement('div')
});

let timer = null;
let lock = false;

ToptipConstructor.prototype.closeToptip = function () {
    instance.animation = 'y-toptip-out';

    setTimeout(() => {
        const el = instance.$el;
        el.parentNode && el.parentNode.removeChild(el);
        lock = false;
    }, 150);

    typeof this.callback === 'function' && this.callback();
};

const Toptip = (options = {}) => {
    instance.animation = '';
    instance.msg = options.msg;
    instance.type = options.type||'success';
    instance.timeout = ~~options.timeout || 5000;
    instance.callback = options.callback;

    if (lock)return;
    lock = true;

    document.body.appendChild(instance.$el);

    instance.$el.addEventListener('click', () => {
        clearTimeout(timer);
        instance.closeToptip();
    });

    timer = setTimeout(() => {
        clearTimeout(timer);
        instance.closeToptip();
    }, instance.timeout);
};

export default Toptip;
